package com.mzpai.product.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.aliyun.opensearch.OpenSearchClient;
import com.aliyun.opensearch.SearcherClient;
import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Lists;
import com.aliyun.opensearch.sdk.dependencies.org.json.JSONObject;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import com.aliyun.opensearch.sdk.generated.search.Config;
import com.aliyun.opensearch.sdk.generated.search.SearchFormat;
import com.aliyun.opensearch.sdk.generated.search.SearchParams;
import com.aliyun.opensearch.sdk.generated.search.general.SearchResult;
import com.aliyun.opensearch.search.SearchParamsBuilder;
import com.gexin.fastjson.JSONArray;
import com.mzpai.util.StringUtils;

public class SearchUtil {
	private static String appName = "productSearch";
    private static String accesskey = "LTAI4GDLQ2Na9U4jPkj6GFMz";
    private static String secret = "8GBVfKRSvEczKjiaTzgridYy2LxFoy";
    private static String host = "http://opensearch-cn-hangzhou.aliyuncs.com";
    private static Logger log = LoggerFactory.getLogger(SearchUtil.class);
    public static String search(String keyword) {
        //创建并构造OpenSearch对象
        OpenSearch openSearch = new OpenSearch(accesskey, secret, host);
        //创建OpenSearchClient对象，并以OpenSearch对象作为构造参数
        OpenSearchClient serviceClient = new OpenSearchClient(openSearch);
        //创建SearcherClient对象，并以OpenSearchClient对象作为构造参数
        SearcherClient searcherClient = new SearcherClient(serviceClient);
        //定义Config对象，用于设定config子句参数，分页或数据返回格式，指定应用名等等
        Config config = new Config(Lists.newArrayList(appName));
        config.setStart(0);
        config.setHits(20);
        //设置返回格式为json，3.1.2 sdk只支持返回xml和json格式，暂不支持返回fulljson类型，3.1.3版本支持fulljson
        config.setSearchFormat(SearchFormat.FULLJSON);
        // 创建参数对象
        SearchParams searchParams = new SearchParams(config);
        // 设置查询子句，若需多个索引组合查询，需要setQuery处合并，否则若设置多个setQuery后面的会替换前面查询
        searchParams.setQuery("store_name:'"+keyword+"'");//通过kfc会搜索出“肯德基”的文档
        List<String> qpname = new ArrayList<String>();
        qpname.add("product");  //设置查询分析名称
        searchParams.setQueryProcessorNames(qpname);
        // SearchParams的工具类，提供了更为便捷的操作
        SearchParamsBuilder paramsBuilder = SearchParamsBuilder.create(searchParams);
        // 执行返回查询结果
        SearchResult searchResult;
        try {
            searchResult = searcherClient.execute(paramsBuilder);
            String result = searchResult.getResult();
            JSONObject obj = new JSONObject(result);
            //判断执行返回是否成功，如果报错执行下面代码，否者输出正确查询内容
            if(obj.get("errors").toString().length()>2){
                JSONArray jsonarr = JSONArray.parseArray(obj.get("errors").toString());
                log.info("开放查询错误 =="+jsonarr.getJSONObject(0).get("code"));
            }else{
                // 输出查询结果
            	return jsonString(obj.toString());
            }
        } catch (OpenSearchException e) {
            e.printStackTrace();
        } catch (OpenSearchClientException e) {
            e.printStackTrace();
        } finally{
        	openSearch.clear();
        }
        return "";
	}
    
    /**
     * 解析开放查询返回结果
     * @param str
     */
    public static String jsonString(String str) {
    	String res = "";
    	try{
	    	JSONObject jsonObject = new JSONObject(str);
	    	JSONObject jsonObject2 = new JSONObject(jsonObject.get("result").toString());
	    	com.aliyun.opensearch.sdk.dependencies.org.json.JSONArray data = jsonObject2.getJSONArray("items");
	    	for(int i=0; i<data.length(); i++) {
	    		Map<String, Object> map=JSON.parseObject(data.get(i).toString());
	    		Map<String, Object> map2=JSON.parseObject(map.get("fields").toString());
	    		if("1".equals(map2.get("is_show"))) {
	    			res  = res + map2.get("id") + ",";
	    		}
	    	}
    	} catch(Exception e) {
    		log.error("解析数据失败 str ={}, {} ", str, e);
    	}
    	return StringUtils.removeLastChar(res);
    }
}
